import { Flex, Image } from '@chakra-ui/react';
import { createSelector } from '@reduxjs/toolkit';
import { skipToken } from '@reduxjs/toolkit/dist/query';
import { stateSelector } from 'store/store';
import { useAppSelector } from 'store/storeHooks';
import { selectLastSelectedImage } from 'features/gallery/store/gallerySelectors';
import { isEqual } from 'lodash-es';
import { memo } from 'react';
import { useGetImageDTOQuery } from 'services/api/endpoints/images';

export const imagesSelector = createSelector(
  [stateSelector, selectLastSelectedImage],
  ({ system }, lastSelectedImage) => {
    const { progressImage, shouldAntialiasProgressImage } = system;
    return {
      imageName: lastSelectedImage?.image_name,
      progressImage,
      shouldAntialiasProgressImage,
    };
  },
  {
    memoizeOptions: {
      resultEqualityCheck: isEqual,
    },
  }
);

const CurrentImagePreview = () => {
  const { imageName, progressImage } = useAppSelector(imagesSelector);

  const { currentData: imageDTO } = useGetImageDTOQuery(imageName ?? skipToken);

  return (
    <Flex
      p="2"
      w="full"
      h="full"
      alignItems="center"
      justifyContent="center"
      position="relative"
      border="1px solid"
      borderColor="inherit"
      rounded="md"
    >
      {progressImage ? (
        <Image
          src={progressImage.dataURL}
          width={progressImage.width}
          height={progressImage.height}
          draggable={false}
          data-testid="progress-image"
          sx={{
            objectFit: 'contain',
            maxWidth: 'full',
            maxHeight: 'full',
            height: 'auto',
            position: 'absolute',
            borderRadius: 'base',
            imageRendering: 'pixelated',
          }}
        />
      ) : (
        <Image
          src={imageDTO?.image_url}
          fallbackStrategy="beforeLoadOrError"
          fallbackSrc={imageDTO?.thumbnail_url}
          draggable={false}
          sx={{
            w: imageDTO?.width,
            objectFit: 'contain',
            maxW: 'full',
            maxH: 'full',
            position: 'absolute',
            borderRadius: 'base',
          }}
        />
      )}
    </Flex>
  );
};

export default memo(CurrentImagePreview);
